<?php
session_start();

$error = '';



// 处理表单注册提交
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {

    //连接数据库
    $servername = "localhost";
    $mysqluser = "root";
    $dbpass = "mysql123456";
    $dbname = "student";
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $mysqluser, $dbpass);
        // $error = '连接成功'; 
    }
    catch(PDOException $e)
    {
        $error = '数据库连接失败: ' . $e->getMessage();
    }

    $id= trim($_POST['id']);
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $password2 = trim($_POST['password2']);
    // 将空字符串转为NULL（根据数据库字段设置选择处理方式）
    $sex = !empty(trim($_POST['sex'])) ? trim($_POST['sex']) : null;
    $phone = !empty(trim($_POST['phone'])) ? trim($_POST['phone']) : null;
    $address = !empty(trim($_POST['addr'])) ? trim($_POST['addr']) : null;

    if ($id==''|| $username == '' || $password == '' || $password2 == ''  ) {
        $error = '请填写所有字段';
    } elseif ($password != $password2) {
        $error = '两次输入的密码不一致';
    } elseif (!ctype_digit($id)) {
        $error = '用户 ID (学号) 必须为整数类型';
    } elseif (strlen($id) < 3) {
        $error = '用户 ID (学号) 长度必须大于 3 个字符';
    } elseif (strlen($password) < 6) {
        $error = '密码长度必须大于 6 个字符';
    } elseif ($phone) {
        if (!ctype_digit($phone)) {
            $error = '手机号码必须为整数类型';
        } elseif (strlen($phone) <= 11) {
            $error = '手机号码长度必须大于 11 个字符';
        }
    } else {
        try {
            // 检查ID是否已存在
            $stmt = $conn->prepare('SELECT id FROM `2402` WHERE id = :id');
            $stmt->execute(['id' => $id]);
            if ($stmt->fetch()) {
                $error = '用户ID (学号)已存在';
                $_SESSION['login_error'] = $error;
                header('Location: register.php');
                exit;
            }
            else {
                // 注册新用户
                 // 修改为参数化查询 
                $sql = "INSERT INTO `2402` 
                        (`id`, `passwd`, `name`, `sex`, `addr`, `phone`) 
                        VALUES 
                        (:id, :password, :username, :sex, :address, :phone)";
                
                $stmt = $conn->prepare($sql);
                
                // 绑定参数（明确处理NULL值）
                $stmt->bindParam(':id', $id, PDO::PARAM_STR);
                $stmt->bindParam(':password', $password, PDO::PARAM_STR);
                $stmt->bindParam(':username', $username, PDO::PARAM_STR);
                $stmt->bindParam(':sex', $sex, $sex ? PDO::PARAM_STR : PDO::PARAM_NULL);
                $stmt->bindParam(':address', $address, $address ? PDO::PARAM_STR : PDO::PARAM_NULL);
                $stmt->bindParam(':phone', $phone, $phone ? PDO::PARAM_STR : PDO::PARAM_NULL);
                
                if ($stmt->execute()) {
                    $error = '注册成功';
                   
                    //注册成功后跳转
                    // header('Location: blog_login.php');
                    // exit;
                }else {
                    $errorInfo = $stmt->errorInfo();
                    $error = '数据库插入失败: ' . $errorInfo[2];
                }
            }

        } catch(PDOException $e) {
            $error = '数据库查询失败: ' . $e->getMessage();
            exit;
        }


    }
    
}



// 记录失败尝试
$_SESSION['attempts'] = ($_SESSION['attempts'] ?? 0) + 1;
if ($_SESSION['attempts'] > 20) {
    // die('请5分钟后再试');
}
// 验证失败时存储错误并跳转回登录页
$_SESSION['login_error'] = $error;
header('Location: register.php');
exit;
?>